using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Threading;
using System.Collections.Generic;
using hedefgrup.reports.renault.database;
using System.Text;
using System.Globalization;
using hedefgrup.reports.renault;
using System.Data.SqlClient;
using hedefgrup.reports.renault.verbatim;
using hedefgrup.reports.renault.date;

public partial class adm_dataImportProgress : reportPage
{
    private SqlConnection newConnection;

    private SqlConnection getConnection()
    {
        if (newConnection == null)
        {
            newConnection = new SqlConnection(base.getConnectionString());
            newConnection.Open();
        }
        return newConnection;
    }

    private SqlCommand prepareCommand(string sql, params object[] args)
    {
        SqlCommand command = new SqlCommand(sql, this.getConnection());
        SqlParameter[] prms = new SqlParameter[args != null ? args.Length : 0];
        for (int i = 0; i < prms.Length; i++) prms[i] = new SqlParameter("@p_" + i, args[i] == null ? string.Empty : args[i]);
        command.Parameters.AddRange(prms);
        return command;
    }

    public void execute(string sql, params object[] args)
    {
        this.prepareCommand(sql, args).ExecuteNonQuery();
    }

    private void verbatimUpload()
    {
        List<string> importData = Session["IMPORT_DATA"] as List<string>;

        verbatimInfo vInfo = verbatimInfo.fromDataFileLine(importData[0]);
        reportMonth monthInfo = new reportMonth(vInfo.Year, vInfo.Month);

        string filter = GetVerbatimFilter();

        this.execute("DELETE renault_verbatim WHERE CARPAN = @p_0 AND Project = @p_1", monthInfo.getMonthYearValue(), vInfo.Project);

        string sqlCommand =
            "INSERT INTO renault_verbatim (AY, YIL, CARPAN, BAYII, IID, Question, Content, MARKA, Interviewee, Satisfaction, Project)" +
            " VALUES " +
            "(@p_0, @p_1, @p_2, @p_3, @p_4, @p_5, @p_6, @p_7, @p_8, @p_9, @p_10)";

        int recordCount = importData.Count + 1;

        int rowsFailed = 0;
        int rowsInserted = 0;
        int i = 1;
        CultureInfo english = CultureInfo.GetCultureInfo("en-US");

        foreach (string line in importData)
        {
            try
            {
                verbatimInfo verbatim = verbatimInfo.fromDataFileLine(line);
                reportMonth lineMonth = new reportMonth(verbatim.Year, verbatim.Month);
                this.execute
                (
                    sqlCommand,
                    lineMonth.getMonth(),
                    lineMonth.getYear(),
                    lineMonth.getMonthYearValue(),
                    verbatim.DealerCode,
                    verbatim.IID,
                    verbatim.QuestionCode,
                    verbatim.Content,
                    verbatim.Make,
                    verbatim.Interviewee,
                    verbatim.Satisfaction,
                    verbatim.Project
                );
                rowsInserted++;
            }
            catch (Exception exp)
            {
                Response.Write("<script>reportFailedRow(" + i + ", \"" + exp.Message + "\");</script>");
                rowsFailed++;
            }
            finally
            {
                i++;
            }

            Response.Write
            (
                String.Format
                (
                    "<script>adjustProgressBar({0},{1},{2});</script>",
                    (100 * i / recordCount).ToString("0.0", english),
                    rowsInserted,
                    rowsFailed
                )
            );
        }

        this.getConnection().Close();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        base.initialize();
        base.ensureAdministratorIsLoggedIn();

        Response.Buffer = false;

        Response.Write
        (
            "<html xmlns='http://www.w3.org/1999/xhtml'>" +
            "<head>" +
                "<title>Data Import Progress</title>" +
            "</head>" +
            "<body style='font-family:Courier New;font-size:12px;'>" +
                "<br /><br /><br /><br /><br /><br /><br /><br />" +
                "<div align=center>" +
                "<table width='600px' border='0px' style='border:1px solid black;'>" +
                    "<tr>" +
                        "<td>" +
                            "Rows Imported: <span id='rowsImported'>0</span>" +
                        "</td>" +
                    "</tr>" +
                    "<tr>" +
                        "<td>" +
                            "Rows Failed: <span id='rowsFailed'>0</span>" +
                        "</td>" +
                    "</tr>" +
                    "<tr>" +
                        "<td>" +
                            "Progress: <span id='totalProgress'>0 %</span>" +
                        "</td>" +
                    "</tr>" +
                    "<tr>" +
                        "<td align='left'>" +
                            "<table id='progressBar'>" +
                                "<tr>" +
                                    "<td style='background-color:blue;width:0px;'>" +
                                        "&nbsp;" +
                                    "</td>" +
                                "</tr>" +
                            "</table>" +
                        "</td>" +
                    "</tr>" +
                    "<tr>" +
                        "<td>" +
                            "<span id='failedRowReport'></span>" +
                        "</td>" +
                    "</tr>" +
                "</table>" +
                "<script>" +
                    "function g(t) { return document.getElementById(t); }" +
                    "function adjustProgressBar(p, n, f)" +
                    "{" +
                        "g('rowsImported').innerHTML = n;" +
                        "g('rowsFailed').innerHTML = f;" +
                        "g('totalProgress').innerHTML = p + '%';" +
                        "g('progressBar').style.width = (p * 6) + 'px';" +
                    "}" +
                    "function reportFailedRow(i, txt)" +
                    "{" +
                        "g('failedRowReport').innerHTML += \"Failed to insert row at position \" + i + \" with error \" + txt + \"<br />\";" +
                    "}" +
                "</script>" +
            "</body>" +
            "</html>"
        );

        if (base.getString("verbatim") == "1")
        {
            verbatimUpload();
            return;
        }

        CultureInfo english = CultureInfo.GetCultureInfo("en-US");
        textFileParser parser = Session["IMPORT_DATA"] as textFileParser;

        int month = Convert.ToInt32(parser.parsedLines[1].getColumnValue("AY"));
        int year = Convert.ToInt32(parser.parsedLines[1].getColumnValue("YIL"));

        SortedList<string, string> columnMappings = Session["IMPORT_COLUMN_MAPPING"] as SortedList<string, string>;
        int recordCount = parser.parsedLines.Count - 1;
        StringBuilder insertCommandFields = new StringBuilder("AY,YIL,BAYII,");
        StringBuilder insertCommandValues = new StringBuilder("@p_0,@p_1,@p_2,");

        int fieldIndex = 3;
        foreach (string dbFieldName in columnMappings.Keys)
        {
            if (!string.IsNullOrEmpty(dbFieldName))
            {
                insertCommandFields.AppendFormat("{0},", dbFieldName);
                insertCommandValues.AppendFormat("@p_{0},", fieldIndex++);
            }
        }

        string sqlCommand = string.Format("INSERT INTO {0} ({1}) VALUES ({2})", base.getDataCache().dataTableName, insertCommandFields.ToString().TrimEnd(','), insertCommandValues.ToString().TrimEnd(','));

        int rowsFailed = 0;
        int rowsInserted = 0;

        this.execute("DELETE " + base.getDataCache().dataTableName + " WHERE AY = @p_0 AND YIL = @p_1", month, year);

        for (int i = 1; i <= recordCount; i++)
        {
            string errorReportTemplate = "Row Number: [{0}], Column Name: [{1}], Value: [{2}]";
            string errorReport = "";
            try
            {
                List<object> parameterValues = new List<object>();

                errorReport = string.Format(errorReportTemplate, 0, "AY", "");
                parameterValues.Add(Convert.ToInt32(parser.parsedLines[i].getColumnValue("AY")));
                errorReport = string.Format(errorReportTemplate, 0, "YIL", "");
                parameterValues.Add(Convert.ToInt32(parser.parsedLines[i].getColumnValue("YIL")));
                errorReport = string.Format(errorReportTemplate, 0, "BAYII", "");
                parameterValues.Add(parser.parsedLines[i].getColumnValue("BAYII").PadLeft(5, '0'));

                foreach (string dbFieldName in columnMappings.Keys)
                {
                    if (!string.IsNullOrEmpty(dbFieldName))
                    {
                        string value = parser.parsedLines[i].getColumnValue(columnMappings[dbFieldName]);
                        errorReport = string.Format(errorReportTemplate, i, dbFieldName, value);
                        parameterValues.Add(string.IsNullOrEmpty(value) ? DBNull.Value : Convert.ChangeType(value, base.getDataCache().columnDefinitions[dbFieldName].dataType));
                    }
                }
                errorReport = string.Format(errorReportTemplate, i, "INSERT COMMAND", "FAILED");
                this.execute(sqlCommand, parameterValues.ToArray());
                rowsInserted++;
            }
            catch (Exception exp)
            {
                Response.Write("<script>reportFailedRow(" + i + ", \"" + errorReport + " / ERROR: " + exp.Message + "\");</script>");
                rowsFailed++;
                return;
            }

            Response.Write
            (
                String.Format
                (
                    "<script>adjustProgressBar({0},{1},{2});</script>",
                    (100 * i / recordCount).ToString("0.0", english),
                    rowsInserted,
                    rowsFailed
                )
            );
        }

        Response.Write("<script>alert(\"START: Setting coordinator and area information for dealers\");</script>");

        try
        {
            db.execute("POST_UPLOAD_" + base.userProjectName.ToUpperInvariant(), true, 120, null);
        }
        catch (Exception postUploadException)
        {
            Response.Write("<script>alert(\"ERROR: " + postUploadException.Message.Replace("\r\n", "\\r\\n").Replace('"', '\'') + "\"</script>");
        }

        Response.Write("<script>alert(\"END: Setting coordinator and area information for dealers\");</script>");
    }
}
